/**
 * 分页组件 tangshijun@ccsuntel.com
 */
function Pager(elem, options, other) {
	// 检查依赖
	if (typeof jQuery == 'undefined') {
		!!console && console.log('jQuery未正确引入');
		return false;
	}
	this.$elem = $(elem);
	this.$other = other;

	// 初始化参数
	this.options = $.extend({
		curPage : 1,
		pageSize : 10,
		totalCount : 0,
		onClick : function(p) {
		}
	}, options || {});

	this.render();
	this.bindEvent();
}
Pager.prototype.init = function(elem, options, other) {
	// 检查依赖
	if (typeof jQuery == 'undefined') {
		!!console && console.log('jQuery未正确引入');
		return false;
	}
	this.$elem = $(elem);
	this.$other = other;
	// 初始化参数
	this.options = $.extend({
		curPage : 1,
		pageSize : 10,
		totalCount : 0,
		onClick : function(p) {
		}
	}, options || {});
	this.render();
	 this.bindEvent();
}
// 渲染分页
Pager.prototype.render = function() {
	
	// 确定总页数
	var countPage = Math.ceil(this.options.totalCount / this.options.pageSize);
	/*
	 * if(countPage < 2){ return false; }
	 */
	this.$elem.empty().html(this.getTpl(this.options.curPage, countPage));
	// alert(this.$other);
	$("#selpagesize").val(this.options.pageSize);

}

// 事件绑定
Pager.prototype.bindEvent = function() {
	var _this = this;
	this.$elem.unbind();
	this.$elem.delegate('a', 'click', function() {
		var $this = $(this);
		if ($this.hasClass('active')) {
			return false;
		}
		var pageIndex = $this.attr('action-data');
		if (!!pageIndex) {
			_this.options.curPage = parseInt(pageIndex);
		} else {
			if ($this.hasClass('prev')) {
				_this.options.curPage--;
			} else if ($this.hasClass('next')) {
				_this.options.curPage++;
			}
		}
		_this.render();
		_this.options.onClick(_this.options.curPage);
	});
}

// 分页模板this.options.pageSize
Pager.prototype.getTpl = function(curPage, countPage) {
	// alert(this.options.pageSize);
	var tplArr = [];

	tplArr.push('共[' + this.options.totalCount + ']条');
	var sel = '<select id="selpagesize" name="selpagesize" onchange="onchangesel(this)" ><option value="10">10条</option><option value="20">20条</option><option value="50">50条</option><option value="100">100条</option></select>';
	tplArr.push(sel);
	if (curPage != 1) {
		tplArr
				.push('<a href="javascript:void(0)" class="prev ui-btn ui-btn-norm">上一页</a>');
	}
	var acClass = '', flag = false;
	for (var i = 1; i <= countPage; i++) {
		acClass = '';
		(i == curPage) && (acClass = 'active');

		if ((i > 1 && i < curPage - 1) || (i < countPage && i > curPage + 1)) {
			if (flag) {
				continue;
			}
			tplArr.push('<span>...</span>');
			flag = true;
		} else {
			tplArr.push('<a href="javascript:void(0)" class="' + acClass
					+ '" action-data="' + i + '">' + i + '</a>');
			flag = false;
		}
	}
	if (curPage < countPage) {
		tplArr
				.push('<a href="javascript:void(0)" class="next ui-btn ui-btn-norm">下一页</a>');
	}
	return tplArr.join('');
}
